package http

import (
	"encoding/json"
	"errors"
	"reflect"
	"time"

	"go-api-template/api/models/system"
	e2 "go-api-template/internal/e"
	"go-api-template/service"
)

// TimeRangeReq 时间范围参数解析
type TimeRangeReq struct {
	StartT  time.Time
	EndT    time.Time
	StartTS int
	EndTS   int
}

func (b *TimeRangeReq) ParseTime(startT, endT string) (err error) {
	b.StartT, err = time.Parse("2006-01-02", startT)
	if err != nil {
		return errors.New("parse startTime fail")
	}

	b.EndT, err = time.Parse("2006-01-02", endT)
	if err != nil {
		return errors.New("parse endTime fail")
	}
	b.StartTS = int(b.StartT.UnixNano() / 1e6)
	b.EndTS = int(b.EndT.AddDate(0, 0, 1).UnixNano() / 1e6)
	return err
}

type JobReq struct {
	IsExport bool   `json:"is_export"`
	JobName  string `json:"-"`
	JobId    string `json:"-"`
	JobHash  string `json:"-"`
	Filename string `json:"filename"`
}

func (b *JobReq) Process(userId, enterpriseId string) {
	service.DB.Model(&system.Job{}).Where("hash = ?", b.JobHash).Update("status", 2)
	if b.Filename != "" {
		service.DB.Model(&system.Job{}).Where("hash = ?", b.JobHash).Update("attachment_address", "/api/base/static/tmp/"+b.Filename)
	}
}

// Resp 统一返回接口体
type Resp struct {
	e2.ResCode
	Data interface{} `json:"data"`
}

type PaginationReq struct {
	Page     int `json:"page"`
	PageSize int `json:"page_size"`
}

// PaginationResp 统一排序返回接口体
type PaginationResp struct {
	e2.ResCode
	Total    int         `json:"total"`
	Page     int         `json:"page"`
	PageSize int         `json:"page_size"`
	Data     interface{} `json:"data"`
}

type RespList[T any] struct {
	Total    int `json:"total"`
	Page     int `json:"page"`
	PageSize int `json:"page_size"`
	Items    []T `json:"items"`
}

func (b *Resp) SetCode(c e2.ResCode) {
	b.Code = c.Code
	b.Msg = c.Msg
}

func (b *Resp) SetData(d interface{}) {
	b.Data = d
}

func (b Resp) IsStructureEmpty() bool {
	return reflect.DeepEqual(b, Resp{})
}

// MarshalBinary 用于处理缓存数据
func (b Resp) MarshalBinary() ([]byte, error) {
	return json.Marshal(b)
}

func (b *Resp) UnmarshalBinary(data []byte) error {
	return json.Unmarshal(data, b)
}
